/**
 * @author phuang5
 * 
 * require language/{xx}_us/qs_options_{xx}_us.js
 * require autocomplete.js
 * 
 */

if (!QSAPI) {
	var QSAPI = {
		Widget : {}
	};
} else if (!QSAPI.Widget) {
	QSAPI.Widget = {};
}

QSAPI.Widget.Options=function(container, option, callback, id){
	var t=QS_Lang.options;
	option = option || {};
	this.container = $(container);
	this.id = id || 'options_id_' + Util.IdProducer.getId();
	this.subContainerStr = {
			header : '<div class="qs-r options_hd qs-api-headbar"></div>',
			options : '<div class="options_container"></div>'
		};	
	this.gKey = null;
	this.lastGKey = null;	
	this.ticker = null;

	this.option = {
			optionsToolBar : {
				position : 'top',
				queryBox : {
					show : true,
					buttonText : t.go
				},
				setting : {
					show : true,
					buttonText : t.settings,
					width : 150,
					height : 200
				}
			},
			showColumns:{
				LastPrice:true,
				Chg:true,
				BidPrice:true,
				AskPrice:true,
				Volume:true,
				OpenInt:true
			},
			fixHeight : true,
			selectedStrategy:1,
			selectedType:1			
		};
	this.callback={
			onLoad:null,
			onStateChange:null, //function(state)
			afterAcceptTicker:null,
			onClick:null //function(row, data)
	}
	this.option.id=this.id;	
	this.option = $.extend(true, this.option, option);
	$.extend(true, this.callback, callback);	
	this.el=$('<div class="qs-gd-light" id="'+this.id+'"><div class="hd"></div><div class="bd"><div class="qs-main"></div></div></div>').appendTo(this.container);
}

QSAPI.Widget.Options.prototype={
	init : function(option) {
		var self=this;
		$.extend(true, self.option , option);
		if (self.optionsWidget){
			self.optionsWidget.clear();
		}
		self.__createOptionsWidget();		
		self.__changeViewList(option);
		$.extend(true, self.optionsWidget.callback , self.callback);
		self.optionsWidget.init(self.option);
		self.optionsWidget.parent=self;
		var w=self.option.width || this.container.width();
		var h=self.option.height || this.container.height();
		self.changeOutSize(w,h);		
    	self.__executeCallback('onLoad');		
	},
	clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
	},
	pauseData:function(){
		if (this.optionsWidget){
			this.optionsWidget.pause();
		}
		this.__unSubscribe(this.tickerObject);
	},
	startData:function(){
		if (this.optionsWidget){
			this.optionsWidget.__subscribe();
		}
		this.__subscribe();
	},
	changeOutSize : function(w, h) {		
		var self=this;
		clearTimeout(self.optionsTimer);
		self.optionsTimer = setTimeout(function() {
			if (w > 0 && w != self.option.width) {
				self.option.width = w;
			}
			if (self.headerbar && h > self.headerbar.outerHeight()
					&& h != self.option.height) {
				self.option.height = self.headerbar ? h	- self.headerbar.outerHeight() : h;
			} else {
				self.option.height = h;
			}
			self.optionsWidget.changeOutSize(self.option.width,
					self.option.height);
			if (self.headerbar) {
				self.headerbar.width(self.option.width);
			}
		}, 200);
	},	
	acceptTicker : function(tickerObject) {
		var self=this;		
		var dm=QSAPI.DataManager;
		if (tickerObject.valid){
			var d;
			self.lastGKey=self.gKey;
			self.gKey=tickerObject.gkey;
	        d = gData[self.gKey] ? gData[self.gKey] : gData[gIdMap[self.gKey]];	 
	        var ticker=d['performanceId']||d['secId'];
	        if (self.gKey==self.lastGKey){
	        	self.__executeCallback('afterAcceptTicker');
	        	return;
	        }
		}else{
			this.__executeCallback('afterAcceptTicker');
			return;
		}
		
		//if (self.optionsWidget.selectedType!=self.optionsWidget.profile.selectedType || self.optionsWidget.selectedType!=self.optionsWidget.profile.selectedStrategy){
		//	console.log('accpetticker rangeFromProfile=true')
			self.optionsWidget.rangeFromProfile=true;
		//}
		
		self.ticker=ticker;
		self.unSubscribeCallballs={
    			onSuccess:function(){
    				self.__unSubscribeEvent();
    			},
    			onFailure:function(){
    				//Log('Main unsubscribe fail')
    				;
    			}
		};
		self.subscribeCallballs={
    			onSuccess:function(){
    				self.__subscribeEvent();
    			},
    			onFailure:function(){;}
		};
		
		if (self.tickerObject){
			self.lastTickerObject=self.tickerObject;
			self.__unSubscribe(self.lastTickerObject);
		}
		self.tickerObject=tickerObject;	
		self.optionsWidget._updateLastPrice(-1);
		//connect data
		self.dataComponent = {
			subscribeID : 'qs_options_root_data_' + self.id,
			updateData : function(tickerObject, data) {
				var d=dm._getData(tickerObject.gkey);
		        if(d && d.LastPrice && d.LastPrice.value != self.optionsWidget.lastPrice){
		        	self.optionsWidget._updateLastPrice(d.LastPrice.value);
				}        
		        self.__updateData(tickerObject.gkey,data);
			}
		};
		self.__subscribe();
		self.optionsWidget.__unSubscribe();		
		self.optionsWidget.addOptions(tickerObject, 
				{
			onBindData:function(index){
				//Log('reBindData, expiration index:'+ index);						
			}
				}); 			
	    self.__executeCallback('afterAcceptTicker');
	},
	__subscribe:function(){
		var self = this;
		var dm=QSAPI.DataManager;
	    if (dm._getType() == dm.TYPE.PUSH){
	    	dm.subscribePush(self.dataComponent, [self.tickerObject],self.subscribeCallballs);
		} else if (dm._getType() == dm.TYPE.PULL) {
			dm.subscribePull(self.dataComponent, [self.tickerObject],self.subscribeCallballs);
		}	
	},
	__unSubscribe:function(targetObject){
		var self = this;
		var dm=QSAPI.DataManager;
		if (dm._getType() == dm.TYPE.PUSH) {
		    dm.unSubscribePush(self.dataComponent, [targetObject],self.unSubscribeCallballs);	    		
		} else if (dm._getType() == dm.TYPE.PULL) {
			dm.unSubscribePull(self.dataComponent, [targetObject],self.unSubscribeCallballs);
		}		    
	},
    __createOptionsWidget:function(){
		var option=$.extend(true,{},this.option);
		var optionsWidget=this.optionsWidget=new QSAPI.Widget.RTQ_Options();		
		optionsWidget.container=$(this.subContainerStr.options).appendTo(this.el);
		optionsWidget.callback=$.extend(true, {}, this.callback);
		if (option.optionsToolBar.setting.show || option.optionsToolBar.queryBox.show){
			var top=option.optionsToolBar.position=='top';
			var bar=null;
			if (top){
				bar=this.headerbar=$(this.subContainerStr.header).insertBefore(optionsWidget.container);
			}else{
				bar=this.headerbar=$(this.subContainerStr.header).insertAfter(optionsWidget.container);
			}
			this.__optionQueryBox(bar, option);
			this.__optionSetting(bar,option);
			optionsWidget.callback = $.extend(true, optionsWidget.callback, {});
		}
}	,
    __executeCallback:function(event,data){
    	if (typeof this.callback[event]=='function'){
    		this.callback[event](data);    		
    	}
    },
    __unSubscribeEvent:function(){
    	//Log('Main ticker unSubscribe');
    },
    __subscribeEvent:function(){
    	//Log('Main ticker subscribe');
    } ,
    __updateData:function(gKey,data){
    	 //Log('Main ticker update data');
    }, 
    __optionSetting:function(container,option){
    	if (option.optionsToolBar.setting.show){    	
    	var settingPanel = this.settingPanel= new QSAPI.Widget.optionsSettingPanel(container);
		var optionsSetting=this.optionsSetting=$('<a href="javascript:void(0)" class="qs-ui-btn setting options-setting">'+option.optionsToolBar.setting.buttonText+'</a>').appendTo(container);
		var id='qs_setting_'+option.id;
		var adjPos=this.__adjustSettingPanelPosition;
        container.find('.options-setting').click(function(e){
            settingPanel.toggle();
            if(settingPanel.getVisible()){
            	adjPos(optionsSetting, settingPanel.el,option.optionsToolBar.position);
            }
        });
    	}    	
    },    
    __optionQueryBox:function(container,option){
		if (option.optionsToolBar.queryBox.show){
			var id='autocomplete_'+option.id;
			var self=this;
			this.quoteQueryBox=$('<input id="'+id+'"  type="text" value="" class="qs-ui-ipt sdk-autocomplete-input"/><a href="javascript:void(0)" class="qs-ui-btn quote-btn go">'+option.optionsToolBar.queryBox.buttonText+'</a>').appendTo(container);
    		var acb=new QSAPI.Widget.AutoComplete(this.container,
    				{category : ["Equities"]},{
    			onClick:function(ticker){
    				if (self.settingPanel){self.settingPanel.hide()};
    				self.acceptTicker(ticker);
    			}    			
    		},id);
    		acb.subscribe(id);
    		$(container).find(".go").bind("click",function(e){
    			acb.trigger(id);
    		});
		}   	
    },     
	__adjustSettingPanelPosition:function(anacliticObject,settingObject,position){
		var so=$(settingObject);
		var ao=$(anacliticObject);
		var left,top;
		if (ao.offset().left+ao.outerWidth()-so.outerWidth()>0){
			left=ao.offset().left+ao.outerWidth()-so.outerWidth();
		}else{
			left=ao.offset().left;
		}		
		if (position=='bottom'){
			top=ao.offset().top-so.outerHeight();
		}else{
			top=ao.offset().top+ao.outerHeight();
		}
		so.css({'top':top,'left':left,'z-Index':10000});
	},
	__changeViewList:function(option){
		if (this.option.showColumns && this.optionsWidget){
			var ow=this.optionsWidget;
			for (var key in this.option.showColumns){
				for (var i=0,len=ow.viewDataList.length;i<len;i++){
					if (ow.viewDataList[i].val==key){
						ow.viewDataList[i].haschecked=this.option.showColumns[key];
						break;
					}
				}
			}
		}
		
	}
};
